package com.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/*
 *  @author 雨安
 *  类名： FastJsonRedisSerializer
 *  创建时间：2024/3/18
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T>{
    //默认字符集
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    //反射类
    private Class<T> clazz;

    //静态块
    static{
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    //公共块
    public FastJsonRedisSerializer(Class<T> clazz){
        super();
        this.clazz = clazz;
    }

    //方法重写
    @Override
    public byte[] serialize(T t)throws SerializationException{
        //判断是否为null
        if (t == null){
            return new byte[0];
        }//返回
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException{
        //判断是否为空或者长度为0
        if (bytes==null || bytes.length <= 0){
            //返回null
            return null;
        }
        //创建一个String字符串并设置字符集
        String str = new String(bytes,DEFAULT_CHARSET);
        //返回
        return JSON.parseObject(str,clazz);
    }


    protected JavaType getJavaType(Class<?> clazz){
        return TypeFactory.defaultInstance().constructType(clazz);
    }

}
